<template>
  <div class="absolute-box">
    <el-dialog
        title="选择新闻的类型"
        v-model="dialogVisible"
        width="400px"
        @close="resetDialog"
    >
      <el-radio-group v-model="selectedType">
        <el-radio value="类型1">武大咨询</el-radio>
        <el-radio value="类型2">珞珈人物</el-radio>
        <el-radio value="类型3">信息发布</el-radio>
        <el-radio value="类型4">校园生活</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNews">确认</el-button>
      </div>
    </el-dialog>
  </div>
  <!-- 顶部标题 -->
    <el-header class="customHeader fixed-header">
      <div class="topBar"></div>
      <div class="headerContent">
        <!-- 左侧：Logo + 分隔线 + 标题 -->
        <div class="headerLeft">
          <img src="../../assets/whu_logo.ico" class="logo" />
          <div class="headerDivider"></div>
          <div class="titleWrapper">
            <div class="mainTitle">讯航<span class="newsText">News</span></div>
            <div class="subTitle">——武大新闻整合平台</div>
          </div>

        </div>

        <div class="headerRightGroup">
          <!-- 右侧：搜索框 -->
          <div class="headerRight">
            <el-input v-model="searchText" placeholder="文章搜索" class="searchInput" clearable  @keyup.enter="handleSearch">
              <template #append>
                <el-button class="custom-search-btn" @click="handleSearch">
                  <!-- 搜索逻辑待写 -->
                  <img src="../../assets/搜索.png" class="search-icon" alt="搜索" />
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </el-header>

    <!-- 添加占位元素避免内容被遮挡 -->
    <div class="header-placeholder"></div>
      <!-- 计院图 -->
      <div class="banner-image">
        <img src="../../assets/R-C.jpg" alt="宣传横幅" style="width: 100%; height: 180px" />
      </div>
  <div class="main-container">
    <div class="news-container">
      <div class="control-container">
        <div class="news-title">{{news.title}}</div>
       <!-- <div class="meta-back-home">回到首页</div> -->
      </div>
      <div class="news-meta">
        <div class="meta-author">作者：{{news.author}}</div>
        <div class="meta-time">发布时间：{{ news.submitTime }}</div>
        <div class="meta-views">浏览量：{{news.pageviews}}</div>
         <div class="meta-views">类型：{{typeText}}</div>
         <el-button type="primary" class="button1" @click="toggleCategoryStatus()">设置分类</el-button>
         <div class="meta-views">状态：{{publishText}}</div>
         <!-- <el-button type="primary" @click="togglePublishStatus()">{{buttonText}}</el-button> -->
          <button @click="togglePublishStatus()" :style="buttonStyle" >
            {{ buttonText }}
        </button>
         <el-button type="primary" :style="buttonStyle1" @click="togglePopularStatus()">{{popularButtonText}}</el-button>
      </div>
      <div class="news-dividing-line"></div>
      <el-button type="primary" class="button2" @click="toggleAbstractStatus()">{{abstractButtonText}}</el-button>
      <div class="abstract-container">
        摘要：
<!--        <div  v-for="(line, index) in displayedLines" :key="index"  style="margin-bottom: 10px;">
        {{line}}
        </div>-->
        <div style="white-space: pre-wrap;">{{ abstractText }}</div>
      </div>

          <div class="news-image" :style="{ backgroundImage: `url(${news.images})` }"></div>

      <div class="news-content multiline">{{news.detail}}</div>
<el-button type="primary" class="button3" @click="deleteNews">删除新闻</el-button>
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
html {
  font-size: 16px; /* 基准字体大小 */
}

body {
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
  color: #0e0d0d;
  line-height: 1.6;
  min-width: 320px;
  overflow-x: hidden;
}

.absolute-box {
  position: absolute;
  margin-top: 21.875rem; /* 350px/16 */
  margin-left: 3.125rem; /* 50px/16 */
  width: 6.25rem; /* 100px/16 */
  height: 43.75rem; /* 700px/16 */
}

.button3 {
  margin-left: 59.375rem; /* 950px/16 */
  margin-top: 1.25rem; /* 20px/16 */
  background-color: skyblue;
  color: white;
  width: 6.25rem; /* 100px/16 */
  height: 1.875rem; /* 30px/16 */
  font-family: "SimSun", sans-serif;
}


.banner-image img {
  display: block; /* 移除图片底部间隙 */
  margin-top: 0px;
}

.topBar {
  height: 1.875rem;
  width: 100%;
  background-color: #b6daff;
}

.button2 {
  margin-top: 0.625rem; /* 10px/16 */
  text-align: center;
  margin-left: 5%;
  width: 6.25rem; /* 100px/16 */
}

.multiline {
  white-space: pre-wrap;
}
 .fixed-header {
  position: fixed !important;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000; /* 确保在最上层 */
  width: 100% !important;
}

/* 占位元素样式 (根据您实际的header高度调整) */
.header-placeholder {
  height: 8.125rem; /* topBar(1.875rem) + headerContent(6.25rem) */
}

/* 标题区域样式 */
.customHeader {
  border-radius: 5%;
  background-color: #ffffff; /* 背景眼色 */
  color: rgb(7, 0, 0); /* 文字颜色 */
  padding: 0 1.25rem;
  height: 6.25rem;
  display: flex;
  align-items: center;
  flex-direction: column; /* 改为垂直布局 */
  box-shadow:
    0 0.25rem 0.5rem rgba(0, 0, 0, 0.1),
    0 0.5rem 1rem rgba(0, 0, 0, 0.1),
    0 0.75rem 1.5rem rgba(0, 0, 0, 0.1); /* 多层叠加阴影，营造立体感 */
}

/* 标题内容样式 */
.headerContent {
  width: 100%;
  height: 20rem;
  display: flex;
  justify-content: space-between; /* 改为左右布局 */
  align-items: center;
}

/* logo样式 */
.logo {
  margin-left: 1.5rem;
  height: 4rem;
  width: auto;
  object-fit: contain;
}

/* 标题容器 */
.titleWrapper {
  display: flex;
  flex-direction: column;
}

/* 主标题样式 */
.mainTitle {
  font-size: 2.1rem;
  font-weight: bold;
  color: #000;
}

/* News文字样式 */
.newsText {
  margin-left: 0.3125rem;
}

/* 副标题样式 */
.subTitle {
  font-size: 1rem;
  color: #409eff; /* Element Plus 主蓝色 */
}

/* 分割线 */
.headerDivider {
  height: 4rem;
  width: 0.06rem;
  background-color: #c9d5f1;
}

/* 新增左侧容器 */
.headerLeft {
  display: flex;
  align-items: center;
  gap: 0.9375rem;
}

  :deep(.el-input__wrapper) {
    /* 移除可能遮挡的样式 */
    overflow: visible;
  }


.search-icon {
  width: 1rem;
  height: 1rem;
  object-fit: contain;
}

.headerRightGroup {
  display: flex;
  align-items: center;
  gap: 1.25rem;
}



.search-icon {
  margin-top: 0.4rem; /* 10px/16 */
  margin-right: 0.5rem; /* 18px/16 */
  height: 1.25rem; /* 30px/16 */
  width: 1.25rem; /* 30px/16 */
  background: url('@/assets/搜索.png') no-repeat center;
  background-size: cover;
  cursor: pointer;
}

.search-icon:hover {
  background-color: rgba(43, 84, 131, 0.1);
}

.custom-input >>> .el-input__wrapper {
  border: none;
  box-shadow: none;
  background-color: transparent;
}

.custom-input >>> input {
  background-color: transparent;
  color: #333;
}

.main-container {
  line-height: 1.75rem; /* 28px/16 */
  background-color: #F2F2F2;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 1rem;
}

.news-container {
  min-height: 43.75rem; /* 700px/16 */
  background-color: white;
  width: 100%;
  max-width: 75rem; /* 1200px/16 */
  padding: 0 1rem 2rem;
  
}

.control-container {
  display: flex;

  margin-top: 1.8125rem; /* 29px/16 */
  height: 6.25rem; /* 100px/16 */
  width: 100%;
  justify-content: center;
}

.news-title {
  font-weight: bold;
  padding-top: 1.3125rem; /* 21px/16 */
  width: 100%;
  height: 6.25rem; /* 100px/16 */
  text-align: center;
  font-size: 1.5rem; /* 37px/16 */
}

.news-meta {
  color:grey;
  font-size: 0.8125rem; /* 13px/16 */
  display: flex;
  height: 1.25rem; /* 20px/16 */
  flex-wrap: wrap;
  gap: 0.9375rem; /* 15px/16 */
  justify-content: center;
}

.meta-author {
  flex: 0 0 auto;
  width:15%
}
 .meta-time{
  width:18%
 }
 .meta-views{
  width:8%
 }

.news-dividing-line {
  margin-top: 1.375rem; /* 22px/16 */
  width: 90%;
  margin-left: 5%;
  height: 1px;
  border: 1px solid #797979;
}

.button1 {
  background-color: skyblue;
  width: 5rem; /* 80px/16 */
  border: none;
  font-family: "SimSun", sans-serif;
  cursor: pointer;
  height: 1.875rem; /* 30px/16 */
}

.abstract-container {
  width: 90%;
  margin-left: 5%;
  font-size: 1.125rem; /* 18px/16 */
  margin-top: 0.8125rem; /* 13px/16 */
}

.news-image {
  width: 100%;
  max-width: 31.25rem; /* 500px/16 */
  height: 25rem; /* 400px/16 */
  margin: 0 auto;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
}

.news-content {
  width: 90%;
  margin: 5%;
  font-size: 1.0625rem; /* 17px/16 */
  margin-top: 0.9375rem; /* 15px/16 */
  padding: 0 1rem;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  html {
    font-size: 14px;
  }
  
  .top-main {
    padding: 0.9375rem 2rem;
  }
  
  .main-search {
    width: 18rem;
    margin-right: 1rem;
  }
}

@media screen and (max-width: 768px) {
  html {
    font-size: 12px;
  }
  
  .absolute-box {
    position: static;
    margin: 1rem auto;
    width: 100%;
    height: auto;
  }
  
  .top-main {
    flex-wrap: wrap;
    height: auto;
    padding: 1rem;
  }
  
  .main-title, .sub-title {
    margin: 0.5rem 0;
    text-align: center;
  }
  
  .main-search {
    width: 100%;
    margin: 1rem 0;
  }
  
  .news-meta {
    flex-direction: column;
    height: auto;
    align-items: center;
  }
  
  .button3 {
    margin-left: auto;
    margin-right: auto;
    display: block;
  }
}

@media screen and (max-width: 480px) {
  .news-title {
    font-size: 1.5rem;
  }
  
  .el-carousel {
    height: 15rem !important;
  }
  
  .el-carousel-item {
    height: 15rem !important;
  }
  
  .news-image {
    height: 15rem !important;
  }
  
  .button1, .button2, .button3 {
    width: 100%;
    margin: 0.5rem 0;
  }
}
</style>


<script>
import {onMounted, reactive, ref} from 'vue'
const searchText = ref('')
import axios from 'axios';
import router from "@/router/index.js";
import {createRouter as $router, useRoute} from "vue-router";

export default {
  setup() {
    const selectedType = ref('类型1')
    const route = useRoute()
    const token=route.query.token
    const id=route.query.id
    const news = reactive({
      id: id,
      title: '',
      detail: '',
      author: '',
      images: '',
      typeId: 0,
      ishot: false,
      submitTime: '',
      summary:null,
      pageviews: 0,
      source: '',
      isPublish:true
    })
    const news1 = reactive({
      id: id
    })
    onMounted(async () => {
      const res = await axios.get('http://localhost:8080/news/'+news.id,{
        headers: {
          Authorization: token
        }
      })
      console.log('token from route.query:', route.query.token)
      console.log('token from route.query:', res.data.data)
      console.log('🚀 headers:', { Authorization: 'Bearer ' + route.query.token });
      Object.assign(news, res.data.data)
    })
    const images = [
      new URL('', import.meta.url).href,
      new URL('', import.meta.url).href,
      new URL('', import.meta.url).href
    ]
    return {
      selectedType,
      token,
      news,
      images,
      news1
    }
  },
  data() {
    return {
      isPopular:false,
      dialogVisible:false,
      isAbstract:false,//摘要是否存在
      searchQuery: '', // 搜索词
      results: [] ,// 搜索结果
      fullContentLines: [
      ],
      displayedText: [],
      currentIndex: 0,
      intervalId: null,
    };
  },
  computed: {
   
     buttonStyle() {
                    return {
                        backgroundColor: this.news.isPublish ? 'skyblue' : 'red', // 浅蓝色和红色
                        color: 'white',
                        width:'80px',
                        border: 'none',
                        borderRadius: '5px',
                        cursor: 'pointer',
                        height:'30px',
                        fontFamily: "SimSun"
                    };
                },
    buttonStyle1() {
                    return {
                        backgroundColor: this.news.ishot ? '#F2F2F2' : 'skyblue',
                        color: this.news.ishot ? 'black': 'white' ,
                        width:'100px',
                        border: 'none',
                        borderRadius: '5px',
                        cursor: 'pointer',
                        height:'30px',
                        fontFamily: "SimSun",
                        marginLeft:'30px',
                    };
                },
    buttonText() {
      return this.news.isPublish ? "下架新闻" : "发布新闻"; // 根据状态显示按钮文本
    },
    publishText(){
       return this.news.isPublish?"已发布":"未发布";
    },
    typeText(){
       console.log(this.selectedType);
      if(this.news.typeId===1){
        return "武大资讯";
      }
      else if(this.news.typeId===2){
        return "珞珈人物";
      }
      else if(this.news.typeId===3){
        return "信息发布";
      }
      else if(this.news.typeId===4){
        return "校园生活";
      }else{
        return "无";
      }
    },

    popularButtonText(){
      return this.news.ishot?"取消热门":"设为热门";
    },
    abstractButtonText(){
       if(this.news.summary===null){
         this.isAbstract=false;
         return "点击生成摘要";
       }else{
         this.isAbstract=true;
         return "重新生成摘要";
       }
    },
    abstractText(){
      if(!this.isAbstract){
        return this.displayedText;
      }
      else{
        this.displayedText=this.news.summary;
        return this.displayedText;
      }
    }

  },
  methods: {
    $router,
    handleSearch() {
      // 监听搜索框输入变化，您可以选择实时搜索
    },
    async updateNews(){
      try {
        const res = await axios.put('http://localhost:8080/news', this.news, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: this.token
        }
      })
        alert(res.data.success ? '更新成功：' : '更新失败：')
      } catch (err) {

      }
    },
    async updateNews1(){
      try {
        const res = await axios.put('http://localhost:8080/news', this.news1, {
          headers: {
            'Content-Type': 'application/json',
            Authorization: this.token
          }
        })
        alert(res.data.success ? '更新成功：' : '更新失败：')
      } catch (err) {

      }
    },
    async getAbstract(){
      try {
        const resa = await axios.post('http://localhost:8080/api/ai/generate-summary/' + this.news.id)
        console.log('111',resa.data)
        await this.updateNews1();
          const res = await axios.get('http://localhost:8080/news/'+this.news.id,{
            headers: {
              Authorization: this.token
            }
          })
        console.log('res.data.data', res.data.data);
        Object.assign(this.news, res.data.data)
        await this.updateNews();
        console.log('this.news.summary',this.news.summary);
        Object.assign(this.fullContentLines, this.news.summary);
      } catch (err) {

      }
    },
    async deleteNews(){
      try {
        const resa = await axios.delete('http://localhost:8080/news/'+this.news.id, {
          headers: {
            'Content-Type': 'application/json',
            Authorization: this.token
          }
        })
        alert(resa.data.success ? '删除成功：' : '删除失败：')
      } catch (err) {

      }
    },
    async onSearch() {
      if (this.searchQuery) {
        try {
          // 发起请求到后端，假设API为 /api/search
          const response = await axios.get('/api/search', {
            params: { query: this.searchQuery }
          });
          this.results = response.data; // 设置搜索结果
        } catch (error) {
          console.error("搜索失败:", error);
        }
      }
    },
    async togglePopularStatus(){//热门设置
      if (this.news.ishot) {
        this.news.ishot = false;
        await this.updateNews();
      } else {
        this.news.ishot = true;
        await this.updateNews();
      }
    },
    async togglePublishStatus() {//新闻发布
      if (this.news.isPublish){
        // 如果已经发布，直接下架
        this.news.isPublish = false;
        await this.updateNews();
      } else {
        if(this.selectedType==='类型4'||this.selectedType==='类型3'||this.selectedType==='类型2'||this.selectedType==='类型1'){
        this.news.isPublish = true;
        await this.updateNews();}
        else{
          alert('未选择类型');
        }
      }
    },
    async submitNews(){
      console.log(this.selectedType);
      if(this.selectedType==='类型1'){
        this.news.typeId=1;
      }
      else if(this.selectedType==='类型2'){
        this.news.typeId=2;
      }
      else if(this.selectedType==='类型3'){
        this.news.typeId=3;
      }
      else if(this.selectedType==='类型4'){
        this.news.typeId=4;
      }else{
        this.news.typeId= null;
      }
      await this.updateNews();
      this.dialogVisible = false;
    },
    toggleCategoryStatus(){
      this.dialogVisible = true;
    },
    async toggleAbstractStatus() {
      if (this.news.summary==null) {
        console.log("第一步");
        await this.getAbstract();
        console.log("第二步");
        await this.startLineGeneration();
        this.isAbstract = !this.isAbstract;
      } else {
        this.isAbstract = !this.isAbstract;
        console.log("正在生成2");
        //this.getAbstract();
        this.fullContentLines = this.news.summary;
        await this.startLineGeneration();
      }

    },
    /*startLineGeneration() {//生成摘要
      this.displayedLines = [];
      this.currentIndex = 0;
      this.intervalId = setInterval(() => {
        if (this.currentIndex < this.fullContentLines.length) {
          this.displayedLines.push(this.fullContentLines[this.currentIndex]);
          this.currentIndex++;
        } else {
          clearInterval(this.intervalId); // 停止生成
        }
      }, 800); // 每 800ms 加一行
    },*/
     async startLineGeneration() {
      clearInterval(this.intervalId);
      console.log("this.fullContentLines",this.fullContentLines);
      const fullText = this.fullContentLines;
      this.displayedText = "";
      let idx = 0;
      const speed = 80;
      this.intervalId = setInterval(() => {
        if (idx < fullText.length) {
          this.displayedText += fullText.charAt(idx);
          idx++;
        } else {
          clearInterval(this.intervalId);
        }
      }, speed);
    },
  beforeUnmount() {
    clearInterval(this.intervalId);
  },
    resetDialog() {
      // 清空选择
    },

  }
};
</script>